import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class YunnanEsxrmzf2f29Policy(BaseTaxPolicySpider):
    name = "yunnan_esxrmzf_2f29_policy"

    province: str = "云南省"  # 取表格
    city: str = "玉溪市"  # 取表格
    county: str = "峨山县"  # 取表格
    park: str = "None"  # 取表格
    source: str = "峨山县人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.yxes.gov.cn/yxgovfront/newPolicy.jspx?path=esxzfxxgk&type=standard&pageNo=1"  # 注明入口网址，以便后续排错
    headers = {
        'Content-Type': 'application/json'
    }
    host = url.split('.gov.cn')[0] + '.gov.cn'

    def start_requests(self):
        for url in [
            self.url,
            "http://www.yxes.gov.cn/yxgovfront/newzfxxgkUnderControl.jspx?path=esxzfxxgk&channelName=ezf&pageNo=1",
            "http://www.yxes.gov.cn/yxgovfront/newzfxxgkUnderControl.jspx?path=esxzfxxgk&channelName=ezbf&pageNo=1",
            "http://www.yxes.gov.cn/yxgovfront/newzfxxgkUnderControl.jspx?path=esxzfxxgk&channelName=ezbt&pageNo=1"
        ]:
            yield scrapy.Request(url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//table//tr//a[(contains(@href, 'html') or contains(@href, 'contentId') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=5]")
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and 'contentId' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath("""//script""").re_first(r"""sCount\s*=\s*'(\d+)""")
            print(int(total_page) // 20)
            for page_num in range(1, math.ceil(int(total_page) / 20) + 1):
                yield response.follow(re.sub(r"pageNo=1", r"pageNo={}".format(page_num), response.url),
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_esxrmzf_2f29_policy".split())
